import { requireAuth } from '~/server/utils/auth'
import CommentService from '~/server/database/services/commentService'
import type { CommentCreationAttributes } from '~/server/database/models/Comment'

export default defineEventHandler(async (event) => {
  try {
    // 验证用户身份
    const user = await requireAuth(event)
    
    // 获取请求体
    const body = await readBody(event)
    const { content, postId, parentId } = body

    // 验证必填字段
    if (!content || !postId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Bad Request',
        data: { message: '评论内容和帖子ID不能为空' }
      })
    }

    // 创建评论数据
    const commentData: CommentCreationAttributes = {
      content: content.trim(),
      postId: parseInt(postId),
      authorId: user.id,
      parentId: parentId ? parseInt(parentId) : undefined
    }

    // 创建评论
    const comment = await CommentService.createComment(commentData)

    // 返回创建的评论
    return {
      success: true,
      data: comment,
      message: '评论创建成功'
    }
  } catch (error: unknown) {
    console.error('创建评论失败:', error)
    
    if (error && typeof error === 'object' && 'statusCode' in error) {
      throw error
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Internal Server Error',
      data: { message: '创建评论失败' }
    })
  }
})
